package work.mediway.mdm.biz.service.hierarchy.impl;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mediway.hos.app.base.seure.util.SecurityUtils;
import com.mediway.hos.common.utils.ExceptionUtil;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import work.mediway.mdm.core.page.QueryRequest;
import work.mediway.mdm.biz.util.MybatisPlusUtil;
import work.mediway.mdm.core.exception.DataException;
import work.mediway.mdm.core.transport.ErrorMsgVO;
import work.mediway.mdm.biz.dto.dict.DictGeneralDTO;
import work.mediway.mdm.biz.entity.hierarchy.HosBusinessUnit;
import work.mediway.mdm.biz.mapper.hierarchy.HosBusinessUnitMapper;
import work.mediway.mdm.biz.service.hierarchy.HosBusinessUnitService;
import work.mediway.mdm.biz.service.common.CommonDictService;

@Slf4j
@Service
@RequiredArgsConstructor
public class HosBusinessUnitServiceImpl extends ServiceImpl<HosBusinessUnitMapper, HosBusinessUnit> implements HosBusinessUnitService {

    private final CommonDictService commonDictService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveHosBusinessUnit(HosBusinessUnit hosBusinessUnit) {
        MybatisPlusUtil.setCreateInfo(hosBusinessUnit, SecurityUtils.getLoginName());
        MybatisPlusUtil.setNullWhenBlank(hosBusinessUnit, HosBusinessUnit.CHECK_ATTR_ARRAY);
        this.save(hosBusinessUnit);
    }

    @Override
    public Page<HosBusinessUnit> findHosBusinessUnit(HosBusinessUnit hosBusinessUnit, QueryRequest queryRequest) {
        Page<HosBusinessUnit> page = new Page<>(queryRequest.getCurrent(), queryRequest.getSize());
        page.setRecords(this.baseMapper.find(page, hosBusinessUnit));
        return page;

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateHosBusinessUnit(HosBusinessUnit hosBusinessUnit) {
        String code = hosBusinessUnit.getBuCode();
        if (StrUtil.isBlank(code)) {
            throw new DataException("BU_Code不能为空");
        }
        if (ObjectUtil.isEmpty(this.baseMapper.findById(code))) {
            throw new DataException(StrUtil.format("【BU_Code = {}】不存在", code));
        }
        MybatisPlusUtil.setUpdateInfo(hosBusinessUnit, SecurityUtils.getLoginName());
        MybatisPlusUtil.setNullWhenBlank(hosBusinessUnit, HosBusinessUnit.CHECK_ATTR_ARRAY);
        this.updateById(hosBusinessUnit);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ErrorMsgVO deleteHosBusinessUnit(String businessUnitId) {
        ErrorMsgVO error = new ErrorMsgVO();
        String[] ids = StrUtil.splitToArray(businessUnitId, StringPool.COMMA);
        for (String id : ids) {
            try {
                //TODO: 删除关联
                this.removeById(id);
            } catch (Exception e) {
                log.error(ExceptionUtil.getExceptionMessage(e), e);
                error.setErrorMsg(id, StrUtil.format("业务单元【BU_Code = {}】删除失败, 失败原因【{}】", id, e.getMessage()));
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        }
        error.setCount(ids.length);
        log.info("删除结果: {}", error);
        return error;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ErrorMsgVO importHosBusinessUnit(List<HosBusinessUnit> hosBusinessUnitList, boolean updateSupport) {
        ErrorMsgVO error = new ErrorMsgVO();
        if (CollUtil.isEmpty(hosBusinessUnitList)) {
            throw new DataException("导入业务单元数据不能为空！");
        }
        for (HosBusinessUnit businessUnit : hosBusinessUnitList) {
            try {
                HosBusinessUnit byId = this.baseMapper.findById(businessUnit.getBuCode());
                if (ObjectUtil.isEmpty(byId)) {
                    this.saveHosBusinessUnit(businessUnit);
                } else if (updateSupport) {
                    MybatisPlusUtil.setUpdateInfo(businessUnit, SecurityUtils.getLoginName());
                    MybatisPlusUtil.setNullWhenBlank(businessUnit, HosBusinessUnit.CHECK_ATTR_ARRAY);
                    this.commonDictService.saveDictDetail(DictGeneralDTO.build(businessUnit, HosBusinessUnit.class), "");
                    this.updateById(businessUnit);
                } else {
                    error.setErrorMsg(businessUnit, StrUtil.format("业务单元【BU_Code = {}】已存在", businessUnit.getBuCode()));
                }
            } catch (Exception e) {
                log.error(ExceptionUtil.getExceptionMessage(e), e);
                error.setErrorMsg(businessUnit, StrUtil.format("业务单元【BU_Code = {}】导入失败, 失败原因【{}】", businessUnit.getBuCode(), e.getMessage()));
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        }
        error.setCount(hosBusinessUnitList.size());
        return error;
    }

    @Override
    public List<HosBusinessUnit> listHosBusinessUnitType() {
        return this.baseMapper.listHosBusinessUnitType();
    }
}
